﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc.Html;
using TjZheng.Framework;
using System.Web.Mvc;

namespace TjZheng.EasyUI
{
    public static partial class EasyUIExtension
    {
        /// <summary>
        /// EasyUI下拉控件
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="name">select的name属性</param>
        /// <param name="selectedValue">选中值</param>
        /// <param name="isRequired">是否必输</param>
        /// <param name="missingMessage">错误信息</param>
        /// <param name="selectList">下拉选项</param> 
        /// <param name="htmlAttributes">html属性</param>
        /// <param name="optionLabel">第一个选项，默认为请选择</param>
        /// <returns></returns>
        public static MvcHtmlString ComboBox(this HtmlHelper htmlHelper, string name, object selectedValue, bool isRequired, string missingMessage, List<SelectListItem> selectList, object htmlAttributes = null, string optionLabel = "==请选择==")
        {
            if (selectList.IsNull())
            {
                return MvcHtmlString.Create("<!--未设置下拉选项-->");
            }
            var objSelectListItem = selectList.FirstOrDefault(c => c.Value == selectedValue.ToString());
            if (objSelectListItem != null)
            {
                objSelectListItem.Selected = true;
            }
            IDictionary<string, object> dataOptions = new Dictionary<string, object>();
            dataOptions["required"] = isRequired.ToString().ToLower();
            if (missingMessage.IsNoNull())
            {
                dataOptions["missingMessage"] = missingMessage.FormatSelf("'{0}'");
            }
            List<string> dataoptionsList = dataOptions.Select(keyValue => keyValue.Key.AppendFormat(":{0}", keyValue.Value)).ToList();
            object data = null;
            IDictionary<string, object> objHtmlAttributes = htmlAttributes.CreateValueDictionary();
            if (objHtmlAttributes.IsNull())
            {
                objHtmlAttributes = new Dictionary<string, object>();
            }
            if (objHtmlAttributes.TryGetValue("dataoptions", out data))
            {
                if (data.ToString().IsNoNull())
                {
                    dataoptionsList.Add(data.ToString());
                }
                objHtmlAttributes.Remove("dataoptions");
            }
            objHtmlAttributes["data-options"] = dataoptionsList.JoinString(",");
            string htmlClass = "easyui-validatebox combobox";
            if (objHtmlAttributes.TryGetValue("class", out data))
            {
                htmlClass = htmlClass.AppendFormat(" {0}", data);
            }
            objHtmlAttributes["class"] = htmlClass;
            return htmlHelper.DropDownList(name, selectList, optionLabel, objHtmlAttributes);
        }
    }
}
